/**
 * 多模型对比测试组件
 * 用于测试真实API调用
 */

import React, { useState } from 'react';
import { Card, Button, Input, Select, Space, Alert, Spin, Typography } from 'antd';
import { PlayCircleOutlined, ReloadOutlined } from '@ant-design/icons';
import { simpleMultiModelService, SimpleComparisonResult } from '../../services/simple-multi-model.service';

const { TextArea } = Input;
const { Option } = Select;
const { Text, Title } = Typography;

export const MultiModelTest: React.FC = () => {
  const [prompt, setPrompt] = useState('请解释什么是人工智能，并举例说明其在日常生活中的应用。');
  const [selectedModels, setSelectedModels] = useState<string[]>(['GPT-4', 'Claude-3-Sonnet']);
  const [loading, setLoading] = useState(false);
  const [results, setResults] = useState<SimpleComparisonResult[]>([]);
  const [error, setError] = useState<string>('');

  const handleTest = async () => {
    if (!prompt.trim() || selectedModels.length === 0) {
      return;
    }

    setLoading(true);
    setResults([]);
    setError('');

    try {
      console.log('开始多模型对比测试...');
      console.log('选中的模型:', selectedModels);
      console.log('提示词:', prompt);

      const comparisonResults = await simpleMultiModelService.compareModels(
        prompt,
        selectedModels,
        2 // 限制并发数
      );

      console.log('对比结果:', comparisonResults);
      setResults(comparisonResults);

      // 检查是否有错误
      const hasErrors = comparisonResults.some(r => r.error);
      if (hasErrors) {
        const errorMessages = comparisonResults
          .filter(r => r.error)
          .map(r => `${r.modelName}: ${r.error}`)
          .join('; ');
        setError(`部分模型调用失败: ${errorMessages}`);
      }

    } catch (error) {
      console.error('多模型对比测试失败:', error);
      setError(error instanceof Error ? error.message : '未知错误');
    } finally {
      setLoading(false);
    }
  };

  const clearResults = () => {
    setResults([]);
    setError('');
  };

  return (
    <div style={{ padding: '24px', maxWidth: '1200px', margin: '0 auto' }}>
      <Title level={2}>多模型对比API测试</Title>
      
      <Alert
        message="API调用测试"
        description="此组件用于测试多模型对比功能是否能正确调用后端API (http://localhost:8002/api/v1/hot-content/generate)"
        type="info"
        showIcon
        style={{ marginBottom: 24 }}
      />

      {/* 测试配置 */}
      <Card title="测试配置" style={{ marginBottom: 24 }}>
        <Space direction="vertical" style={{ width: '100%' }} size="middle">
          <div>
            <Text strong>测试提示词：</Text>
            <TextArea
              rows={3}
              value={prompt}
              onChange={(e) => setPrompt(e.target.value)}
              placeholder="输入测试提示词..."
              style={{ marginTop: 8 }}
            />
          </div>

          <div>
            <Text strong>选择测试模型：</Text>
            <Select
              mode="multiple"
              style={{ width: '100%', marginTop: 8 }}
              placeholder="选择要测试的模型"
              value={selectedModels}
              onChange={setSelectedModels}
            >
              {simpleMultiModelService.getAvailableModels().map(model => (
                <Option key={model} value={model}>
                  {model}
                </Option>
              ))}
            </Select>
          </div>

          <div style={{ textAlign: 'center' }}>
            <Space>
              <Button
                type="primary"
                icon={<PlayCircleOutlined />}
                onClick={handleTest}
                loading={loading}
                disabled={!prompt.trim() || selectedModels.length === 0}
                size="large"
              >
                开始API测试
              </Button>
              <Button
                icon={<ReloadOutlined />}
                onClick={clearResults}
                disabled={loading}
              >
                清空结果
              </Button>
            </Space>
          </div>
        </Space>
      </Card>

      {/* 错误信息 */}
      {error && (
        <Alert
          message="测试错误"
          description={error}
          type="error"
          showIcon
          style={{ marginBottom: 24 }}
        />
      )}

      {/* 加载状态 */}
      {loading && (
        <Card style={{ textAlign: 'center', marginBottom: 24 }}>
          <Spin size="large" />
          <p style={{ marginTop: 16 }}>正在调用后端API测试 {selectedModels.length} 个模型...</p>
          <Text type="secondary">API地址: http://localhost:8002/api/v1/hot-content/generate</Text>
        </Card>
      )}

      {/* 测试结果 */}
      {results.length > 0 && (
        <Card title={`API测试结果 (${results.length}/${selectedModels.length})`} style={{ marginBottom: 24 }}>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(400px, 1fr))', gap: '16px' }}>
            {results.map((result, index) => (
              <Card
                key={result.modelName}
                title={
                  <Space>
                    <span>{result.modelName}</span>
                    {result.error ? (
                      <span style={{ color: '#ff4d4f' }}>❌ 失败</span>
                    ) : (
                      <span style={{ color: '#52c41a' }}>✅ 成功</span>
                    )}
                  </Space>
                }
                size="small"
                extra={
                  !result.error && (
                    <Space>
                      <Text type="secondary">{result.duration}ms</Text>
                      <Text type="secondary">${result.cost}</Text>
                    </Space>
                  )
                }
              >
                {result.error ? (
                  <Alert 
                    message="API调用失败" 
                    description={result.error} 
                    type="error" 
                    size="small"
                  />
                ) : (
                  <>
                    <div style={{ marginBottom: 12 }}>
                      <Space split={<span>|</span>}>
                        <Text type="secondary">输入: {result.tokenUsage?.prompt || 0} tokens</Text>
                        <Text type="secondary">输出: {result.tokenUsage?.completion || 0} tokens</Text>
                        <Text type="secondary">总计: {result.tokenUsage?.total || 0} tokens</Text>
                      </Space>
                    </div>
                    
                    <div style={{ 
                      maxHeight: '300px', 
                      overflow: 'auto', 
                      padding: '12px',
                      backgroundColor: '#f5f5f5',
                      borderRadius: '6px',
                      whiteSpace: 'pre-wrap',
                      fontSize: '14px',
                      lineHeight: '1.6'
                    }}>
                      {result.content || '无内容返回'}
                    </div>
                  </>
                )}
              </Card>
            ))}
          </div>

          {/* API调用统计 */}
          {results.length === selectedModels.length && (
            <div style={{ marginTop: 16, padding: '16px', backgroundColor: '#f0f2f5', borderRadius: '8px' }}>
              <Title level={5}>API调用统计</Title>
              {(() => {
                const stats = simpleMultiModelService.getModelStats(results);
                return (
                  <Space size="large" wrap>
                    <Text>成功率: <strong>{stats.successRate}%</strong></Text>
                    <Text>平均响应时间: <strong>{stats.averageResponseTime}ms</strong></Text>
                    <Text>总成本: <strong>${stats.totalCost}</strong></Text>
                    {stats.fastestModel && <Text>最快模型: <strong>{stats.fastestModel}</strong></Text>}
                  </Space>
                );
              })()}
            </div>
          )}
        </Card>
      )}

      {/* 调试信息 */}
      <Card title="调试信息" size="small">
        <Space direction="vertical" style={{ width: '100%' }}>
          <Text><strong>后端API地址:</strong> http://localhost:8002/api/v1/hot-content/generate</Text>
          <Text><strong>可用模型:</strong> {simpleMultiModelService.getAvailableModels().join(', ')}</Text>
          <Text><strong>请求方法:</strong> POST</Text>
          <Text><strong>请求头:</strong> Content-Type: application/json</Text>
        </Space>
      </Card>
    </div>
  );
};
